package me.zhanshi123.vipsystem.command.sub;

import me.zhanshi123.vipsystem.api.VipSystemAPI;
import me.zhanshi123.vipsystem.api.storage.VipStorage;
import me.zhanshi123.vipsystem.command.SubCommand;
import me.zhanshi123.vipsystem.command.type.PermissionCommand;
import me.zhanshi123.vipsystem.manager.MessageManager;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

public class SwitchVipCommand extends SubCommand implements PermissionCommand {

    public static HashMap<UUID, Long> baffle = new HashMap<>();

    public static Boolean hasNext(Player player) {
        long current = System.currentTimeMillis();
        long time = baffle.computeIfAbsent(player.getUniqueId(), v -> 0L);
        if (current >= time) {
            baffle.put(player.getUniqueId(), current + 10000);
            return true;
        }
        return false;
    }

    public SwitchVipCommand() {
        super("switch", MessageManager.getString("Command.switch.usage"), MessageManager.getString("Command.switch.desc"));
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        Player player = Bukkit.getPlayer(args[1]);
        String vipName = args[2];
        if (player != null && player.isOnline()) {
            if (hasNext(player)) {
                Set<VipStorage> data = VipSystemAPI.getInstance().getVipStorageManager().getVipStorage(player);
                if (!data.isEmpty()) {
                    Optional<VipStorage> storage = data.stream().filter(vipStorage -> vipStorage.getVip().equals(vipName)).findFirst();
                    if (storage.isPresent()) {
                        int id = storage.get().getId();
                        VipSystemAPI.getInstance().getVipStorageManager().changedVipStorageById(player, id);
                        player.sendMessage(MessageFormat.format(MessageManager.getString("Command.switch.success"), vipName));
                        return true;
                    }
                }
                player.sendMessage(MessageFormat.format(MessageManager.getString("Command.switch.failure"), vipName));
            } else {
                player.sendMessage(MessageFormat.format(MessageManager.getString("Command.switch.baffle"), vipName));
            }
        } else {
            sender.sendMessage(MessageManager.getString("playerNotFound"));
        }
        return true;
    }
}
